package modulos;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.border.Border;

import auxiliary.Constants;
import auxiliary.Database;

public class PanelProducto extends JPanel implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	ArrayList<ArrayList<String>> listOfProductos;
	ArrayList<ArrayList<String>> listOfMaquinaria;
	Database db;
	ArrayList<JRadioButton> radiobuttons;
	ButtonGroup group;
	JPanel radioPanel;
	int currentButton;
	JTable jt;
	TableModelProducto ptm;
	PanelProducto panel;
	ImageIcon imageicon,add,delete,modify,redicon,greenicon;
	JLabel imagelabel;

	// ProductoButtonHandler handler;

	public PanelProducto() {
		panel = this;
		db = new Database();
		
		listOfProductos = db.retrieveProductos();
		currentButton = 0;
		// String[] strArray = new String[listOfProductos.size()];

		ptm = new TableModelProducto();
		jt = new JTable(ptm);
		ptm.updateTable();
		setColumnWidth();

		URL imgURL = ClassLoader.getSystemResource("images/back.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);

		imageicon = new ImageIcon(image);
		imagelabel = new JLabel(imageicon);
		
		imgURL = ClassLoader.getSystemResource("images/red.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		redicon = new ImageIcon(image);
		
		Image img = redicon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		redicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/green.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		greenicon = new ImageIcon(image);
		
		img = greenicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		greenicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/add.png");
		img = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		add = new ImageIcon(img);
		
		img = add.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		add = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/delete.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		delete = new ImageIcon(image);
		
		img = delete.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		delete = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/modify.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		modify = new ImageIcon(image);
		
		img = modify.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		modify = new ImageIcon(newimg);

		radiobuttons = new ArrayList<JRadioButton>();
		for (Integer i = 0; i < listOfProductos.size(); i++) {
			radiobuttons.add(new JRadioButton());
			radiobuttons.get(i).setSize(20, 20);

			radiobuttons.get(i).setActionCommand(i.toString());
			radiobuttons.get(i).addActionListener(this);
			// System.out.println(radiobuttons.get(i).getActionCommand());
			// Group the radio buttons.
			radiobuttons.get(0).setSelected(true);
		}

		group = new ButtonGroup();

		radioPanel = new JPanel();
		radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));

		radioPanel.add(Box.createRigidArea(new Dimension(5, 2)));
		for (int i = 0; i < listOfProductos.size(); i++) {

			group.add(radiobuttons.get(i));
			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		jt.setEnabled(false);
		jt.setRowHeight(22);
		jt.getTableHeader().setReorderingAllowed(false);
		jt.getTableHeader().setFont(new Font("Dialog", Font.BOLD, 14));
		
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(radioPanel,BorderLayout.WEST);
		JViewport jv = new JViewport();
		jv.setView(panel);

		
		JScrollPane jsp = new JScrollPane(jt);
		jsp.setRowHeader(jv);

		JButton addbutton = new JButton("Agregar",add);
		addbutton.setActionCommand(Constants.PRODUCTO_AGREGAR);
		addbutton.addActionListener(this);

		JButton removebutton = new JButton("Eliminar",delete);
		removebutton.setActionCommand(Constants.PRODUCTO_ELIMINAR);
		removebutton.addActionListener(this);

		JButton modifybutton = new JButton("Modificar",modify);
		modifybutton.setActionCommand(Constants.PRODUCTO_MODIFICAR);
		modifybutton.addActionListener(this);

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		// JPanel bottomPanel = new JPanel(new BorderLayout());
		JPanel topPanel = new JPanel(new BorderLayout());

		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(addbutton, BorderLayout.WEST);
		buttonPanel.add(modifybutton, BorderLayout.CENTER);
		buttonPanel.add(removebutton, BorderLayout.EAST);
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(imagelabel, BorderLayout.EAST);

		topPanel.add(jsp, BorderLayout.CENTER);
		//topPanel.add(radioPanel, BorderLayout.WEST);

		// bottomPanel.add(buttonPanel,BorderLayout.CENTER);

		this.setLayout(new BorderLayout());
		this.add(topPanel, BorderLayout.NORTH);
		this.add(buttonPanel, BorderLayout.SOUTH);

		this.setVisible(true);

	}

	private void setColumnWidth() {

		jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		jt.getColumnModel().getColumn(0).setPreferredWidth(160);
		jt.getColumnModel().getColumn(1).setPreferredWidth(70);
		jt.getColumnModel().getColumn(2).setPreferredWidth(50);

		jt.getColumnModel().getColumn(3).setPreferredWidth(50);
		jt.getColumnModel().getColumn(4).setPreferredWidth(70);
		jt.getColumnModel().getColumn(5).setPreferredWidth(70);
		jt.getColumnModel().getColumn(6).setPreferredWidth(70);
		jt.getColumnModel().getColumn(7).setPreferredWidth(400);
		jt.getColumnModel().getColumn(8).setPreferredWidth(200);
		jt.getColumnModel().getColumn(9).setPreferredWidth(150);
	}

	void addRadioButton() {
		Integer buttonindex = listOfProductos.size() - 1;

		radiobuttons.add(new JRadioButton());
		radiobuttons.get(buttonindex).setSize(20, 20);
		radiobuttons.get(buttonindex).setActionCommand(buttonindex.toString());
		radiobuttons.get(buttonindex).addActionListener(this);

		group.add(radiobuttons.get(buttonindex));
		//radioPanel.add(radiobuttons.get(buttonindex));

		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(5, 2)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}
		
		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());
		}
		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	void deleteRadioButton(int button) {
		final int curr = button;

		//radioPanel.remove(radiobuttons.get(curr));
		group.remove(radiobuttons.get(curr));
		radiobuttons.remove(curr);
		
		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(5, 2)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());
		}
		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	public void updateTable() {
		ptm.updateTable();
		setColumnWidth();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		if (command == Constants.PRODUCTO_AGREGAR) {

			String[] labels = { "Nombre", "Unidad", "Tiempo Dispensacion Lote",
					"Tiempo Produccion Lote", "Etiquetadas/Hora",
					"Bandas/Hora", "Empacadas/Hora", "Loteado", "Maquinas Produccion",
					"Maquinas Llenado", "Maquinas Loteado" };
			int[] widths = { 15, 15, 3, 3, 3, 3, 3, 3, 20, 20, 20 };
			String[] descs = { "Nombre", "Unidad", "Tiempo Dispensacion Lote",
					"Tiempo Produccion Lote", "Etiquetadas/Hora",
					"Bandas/Hora", "Empacadas/Hora", "Loteado", "Maquinas Produccion",
					"Maquinas Llenado", "Maquinas Loteado" };

			new AgregarProducto(jt, labels, widths, descs, Constants
					.getParentFrame(this));
			// agregar.setVisible(true);

		}

		else if (command == Constants.PRODUCTO_ELIMINAR) {

			String[][] allvalues = Constants.arrayListToString(listOfProductos);

			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));
			String[] values = list.toArray(new String[0]);

			boolean deleted = db.deleteProducto(values);

			if (deleted) {
				listOfProductos = db.retrieveProductos();

				ptm.updateTable();

				deleteRadioButton(currentButton);

				radioPanel.revalidate();
				radioPanel.repaint();

				setColumnWidth();
			} else {
				JOptionPane
						.showMessageDialog(
								new JFrame(),
								"Error: Borre primero items de produccion mensual que referencian producto",
								"Mensaje de Error", JOptionPane.ERROR_MESSAGE);
			}

			// panel.revalidate();
			// panel.repaint();

		}

		else if (command == Constants.PRODUCTO_MODIFICAR) {

			int labelsLength;

			listOfProductos = db.retrieveProductos();

			String[][] allvalues = Constants.arrayListToString(listOfProductos);

			int size = allvalues[currentButton].length;

			// System.out.println("size=" + size);

			String[] labels = { "Nombre", "Unidad", "Tiempo Dispensacion Lote",
					"Tiempo Produccion Lote", "Etiquetadas/Hora",
					"Bandas/Hora", "Empacadas/Hora", "Loteado" };
			Integer[] widths = { 15, 15, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15,
					15, 15, 15, 15 };
			String[] descs = { "Nombre", "Unidad", "Tiempo Dispensacion Lote",
					"Tiempo Produccion Lote", "Etiquetadas/Hora",
					"Bandas/Hora", "Empacadas/Hora", "Loteado"};

			labelsLength = 9;
			int i;
			for (i = 9; i < size-3; i++) {
				String array[] = allvalues[currentButton][i].split(",");

				labelsLength += array.length;
				labels = (String[]) Constants.concat(labels,
						new String[] { allvalues[currentButton][i] });
				descs = (String[]) Constants.concat(descs,
						new String[] { allvalues[currentButton][i] });
			}

			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));
			String[] values = list.toArray(new String[0]);

			new ModificarProducto(labels, widths, descs, values, labelsLength,
					Constants.getParentFrame(this));
		}
		else {
			currentButton = Integer.valueOf(e.getActionCommand());
		}
		
		System.out.println(command);

	}

	public class AgregarProducto extends JDialog implements ActionListener {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Container contentPane;
		JPanel form;
		JTextField[] fields;
		ArrayList<String[]> maquinariaIds;
		// ButtonHandler handler;
		// Database db;
		JList list[];
		// FuncionarioPanel panel;
		AgregarProducto agregarDialog;
		JCheckBox boxes[];

		public AgregarProducto(JTable jt, final String[] labels,
				final int[] widths, final String[] tips, JFrame parent) {
			super(parent, "Agregar Producto",
					Dialog.ModalityType.DOCUMENT_MODAL);

			agregarDialog = this;
			maquinariaIds = new ArrayList<String[]>();

			contentPane = getContentPane();
			
			boxes = new JCheckBox[3];
			
			form = new JPanel(new BorderLayout());

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion del Producto");

			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));

			JPanel alllistforms = new JPanel();
			alllistforms
					.setLayout(new BoxLayout(alllistforms, BoxLayout.Y_AXIS));

			JPanel listform[] = new JPanel[3];
			for (int i = 0; i < 3; i++) {
				listform[i] = new JPanel();
				Border temp = BorderFactory.createTitledBorder(loweredbevel,
						i == 0 ? "Maquinas Asignadas para Produccion"
								: (i == 1 ? "Maquinas Asignadas para Llenado"
										: "Maquinas Asignadas para Loteado"));
				listform[i].setBorder(temp);
				alllistforms.add(listform[i]);
			}

			form.setBorder(border);

			JPanel buttonPanel = new JPanel();

			JPanel labelPanel = new JPanel(new GridLayout(labels.length - 3, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length - 3, 1));

			fieldPanel.setBorder(grayborder);

			form.add(labelPanel);
			form.add(Box.createRigidArea(new Dimension(10, 25)));

			form.add(fieldPanel);

			fields = new JTextField[labels.length];

			listOfMaquinaria = db.retrieveMaquinaria();
			System.out.println(listOfMaquinaria);

			int boxcount =0;
			for (int i = 0; i < labels.length - 3; i++) {
				fields[i] = new JTextField();
				if (i < tips.length)
					fields[i].setToolTipText(tips[i]);
				if (i < widths.length)
					fields[i].setColumns(widths[i]);

				JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
				lab.setLabelFor(fields[i]);
				labelPanel.add(lab);
				JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
				if(i!=labels.length-4)
					p.add(fields[i]);
				
				if (i == labels.length - 7 || i == labels.length - 6 || i == labels.length - 4 ) {
					// fields[i].addFocusListener(focushandler);
					fields[i].setEnabled(false);
					boxes[boxcount] = new JCheckBox();
					boxes[boxcount].addActionListener(this);
					boxes[boxcount].setActionCommand("checkboxCommand" + boxcount);
					p.add(boxes[boxcount]);
					fieldPanel.add(p);
					//fieldPanel.add(boxes[boxcount]);
					boxcount++;
				}
				else {
					fieldPanel.add(p);
				}
			}

			list = new JList[3];

			for (int i = labels.length - 3, j = 0; i < labels.length; i++, j++) {

				JPanel listLabelPanel = new JPanel(new GridLayout(1, 1));
				JPanel listPanel = new JPanel(new GridLayout(1, 1));

				JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
				lab.setLabelFor(fields[i]);
				listLabelPanel.add(lab);

				JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));

				listOfMaquinaria = db.retrieveMaquinaria(j);
				//System.out.println(listOfMaquinaria);
				list[j] = new JList(Constants.arrayListToStringSelect(
						listOfMaquinaria, 1, 2));
				maquinariaIds.add(Constants.arrayListToStringSelect(
						listOfMaquinaria, 0, 1));

				list[j].setFixedCellWidth(175);
				list[j].setVisibleRowCount(5);
				if(j==2) {
					list[j].setVisibleRowCount(3);
					list[j].setEnabled(false);
				}
				JScrollPane scrollpane;
				//if(j == 2) {
				
//					JPanel loteadopanel = new JPanel(new BorderLayout());
//					loteadopanel.add(list[j],BorderLayout.CENTER);
//					loteadopanel.add(new JCheckBox(),BorderLayout.EAST);
//					scrollpane = new JScrollPane(loteadopanel);
				
				//} else {
					scrollpane = new JScrollPane(list[j]);
				//}

				p.add(scrollpane);
				listPanel.add(p, BorderLayout.CENTER);

				// listform[j].add(listLabelPanel);
				listform[j].add(listPanel);

			}

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.PRODUCTO_AGREGAR_CANCELAR);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.PRODUCTO_AGREGAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);

			contentPane.add(form, BorderLayout.NORTH);
			contentPane.add(alllistforms, BorderLayout.CENTER);
			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);
			pack();

			setVisible(true);
		}

		public void actionPerformed(ActionEvent e) {

			ArrayList<String> productoData;
			ArrayList<String> fasesData;
			ArrayList<String> maquinariaProduccionData;
			ArrayList<String> maquinariaLlenadoData;
			ArrayList<String> maquinariaLoteadoData;

			fasesData = new ArrayList<String>();
			productoData = new ArrayList<String>();
			maquinariaProduccionData = new ArrayList<String>();
			maquinariaLlenadoData = new ArrayList<String>();
			maquinariaLoteadoData = new ArrayList<String>();

			// check if all info is entered

			String command = e.getActionCommand();

			if (command == Constants.PRODUCTO_AGREGAR_CONFIRMACION) {

				boolean validtiempodispensacion = true;
				boolean validetiquetadas = true;
				boolean validbandas = true;
				boolean validempacadas = true;

				boolean indicescheck[] = new boolean[] { true, true, true };

				try {
					Float.parseFloat(fields[2].getText());

				} catch (Exception exp) {
					validtiempodispensacion = false;
				}

				try {
					Integer.parseInt(fields[3].getText());

				} catch (Exception exp) {
					validetiquetadas = true;
				}

				try {
					Integer.parseInt(fields[4].getText());

				} catch (Exception exp) {
					validbandas = true;
				}

				try {
					Integer.parseInt(fields[5].getText());

				} catch (Exception exp) {
					validempacadas = true;
				}

				if (list[0].getSelectedIndices().length == 0) {
					indicescheck[0] = false;
				}

				if (list[1].getSelectedIndices().length == 0) {
					indicescheck[1] = false;
				}

				if (list[2].getSelectedIndices().length == 0) {
					indicescheck[2] = true;
				}

				if (validtiempodispensacion && validetiquetadas && validbandas
						&& validempacadas && indicescheck[0] && indicescheck[1]
						&& indicescheck[2]) {

					for (int i = 0; i < fields.length - 3; i++) {
						productoData.add(fields[i].getText());
					}
					
					for (int i = 0; i < 3; i++) {
						fasesData.add(String.valueOf(boxes[i].isSelected()));
					}

					int[] indices = list[0].getSelectedIndices();

					for (int i = 0; i < list[0].getSelectedIndices().length; i++) {
						System.out.println("maquinariaIdslength"
								+ maquinariaIds.get(0).length);
						System.out.println("indices" + indices.length);

						maquinariaProduccionData
								.add(maquinariaIds.get(0)[indices[i]]);
						// productoData.add(fields[i].getText());
					}

					indices = list[1].getSelectedIndices();

					for (int i = 0; i < list[1].getSelectedIndices().length; i++) {
						maquinariaLlenadoData
								.add(maquinariaIds.get(1)[indices[i]]);
						// productoData.add(fields[i].getText());
					}

					indices = list[2].getSelectedIndices();

					for (int i = 0; i < list[2].getSelectedIndices().length; i++) {
						maquinariaLoteadoData
								.add(maquinariaIds.get(2)[indices[i]]);
						// productoData.add(fields[i].getText());
					}

					db.insertProducto(productoData, fasesData, maquinariaProduccionData,
							maquinariaLlenadoData, maquinariaLoteadoData);

					listOfProductos = db.retrieveProductos();

					ptm.updateTable();

					addRadioButton();
					radioPanel.revalidate();
					radioPanel.repaint();
					agregarDialog.dispose();

					setColumnWidth();
				} else {
					JOptionPane
							.showMessageDialog(
									this,
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validtiempodispensacion ? ""
													: "- Ingrese un numero valido para tiempo de dispensacion\n")
											+ (validetiquetadas ? ""
													: "- Ingrese un numero valido para unidades etiquetadas por hora\n")
											+ (validbandas ? ""
													: "- Ingrese un numero valido para unidades bandas por hora\n")
											+ (validempacadas ? ""
													: "- Ingrese un numero valido para unidades empacadas por hora\n")
											+ (indicescheck[0] ? ""
													: "- Seleccione al menos una maquina para produccion\n")
											+ (indicescheck[1] ? ""
													: "- Seleccione al menos una maquina para llenado\n")
											+ (indicescheck[2] ? ""
													: "- Seleccione al menos una maquina para loteado\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}

			} else if(command.equals(Constants.PRODUCTO_AGREGAR_CANCELAR)) { 
				agregarDialog.dispose();
			}
			else if (command.equals("checkboxCommand0")) {
				if(boxes[0].isSelected())
					fields[4].setEnabled(true);
				else 
					fields[4].setEnabled(false);
				
			} else if (command.equals("checkboxCommand1")) {
				if(boxes[1].isSelected())
					fields[5].setEnabled(true);
				else 
					fields[5].setEnabled(false);
			} else if (command.equals("checkboxCommand2")) {
				if(boxes[2].isSelected())
					list[2].setEnabled(true);
				else 
					list[2].setEnabled(false);
				}
				else {
					//System.out.println(command);
			}
		}
	}

	public class ModificarProducto extends JDialog implements ActionListener {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Container contentPane;
		JPanel form;
		JTextField[] fields;
		ArrayList<JTextField>[] secondaryfields;
		ArrayList<JCheckBox>[] secondarycheckboxes;
		String hiddenfield;
		// Database db;
		ModificarProducto modificarFrame;
		ArrayList<String> maquinariaValues;
		ArrayList<String> fases;
		String values[], maqValues[];
		JCheckBox boxes[];
		boolean maqModifications[];

		@SuppressWarnings("unchecked")
		public ModificarProducto(final String[] labels, final Integer[] widths,
				final String[] tips, final String[] values,
				final int labelsLength, JFrame parent) {

			super(parent, "Modificar Producto",
					Dialog.ModalityType.DOCUMENT_MODAL);

			String[][] allvalues = Constants.arrayListToString(listOfProductos);
			maquinariaValues = new ArrayList<String>();
			fases = new ArrayList<String>();
			boxes = new JCheckBox[3];

			int id = Integer.valueOf(allvalues[currentButton][0]);

			modificarFrame = this;
			contentPane = getContentPane();
			form = new JPanel(new BorderLayout());

			// Border grayborder = BorderFactory
			// .createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion del Producto");

			Border grayborder = BorderFactory
			.createLineBorder(Color.LIGHT_GRAY);
			
			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));

			JPanel alllistforms = new JPanel();
			alllistforms
					.setLayout(new BoxLayout(alllistforms, BoxLayout.Y_AXIS));

			JScrollPane scrollpane[] = new JScrollPane[3];
			JPanel listform[] = new JPanel[3];

			for (int i = 0; i < 3; i++) {
				listform[i] = new JPanel(new BorderLayout());
				
				/*listform[i].setLayout(new BoxLayout(listform[i],
						BoxLayout.X_AXIS));*/
				Border temp = BorderFactory.createTitledBorder(loweredbevel,
						i == 0 ? "Maquinas Asignadas para Produccion"
								: (i == 1 ? "Maquinas Asignadas para Llenado"
										: "Maquinas Asignadas para Loteado"));
				listform[i].setBorder(temp);
				alllistforms.add(listform[i]);
			}

			form.setBorder(border);

			// JPanel form = new JPanel(new BorderLayout());
			JPanel buttonPanel = new JPanel();

			JPanel labelPanel = new JPanel(new GridLayout(labels.length - 2, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length - 2, 1));

			fieldPanel.setBorder(grayborder);
			
			form.add(labelPanel);
			form.add(Box.createRigidArea(new Dimension(10, 25)));
			form.add(fieldPanel);

			fields = new JTextField[labels.length];

			hiddenfield = values[0];
			
			boxes[0] = new JCheckBox();
			boxes[1] = new JCheckBox();
			boxes[2] = new JCheckBox();
			
		
			String maquinariaLabels[] = { "---- Maquinas Produccion ---",
					"---- Maquinas Llenado ------",
					"---- Maquinas Loteado ------" };

			int lengthMaqValues = 0;

			secondaryfields = new ArrayList[3];
			secondarycheckboxes = new ArrayList[3];

			
			for (int i = 0; i < labels.length; i++) {

				if (i > 6) {

					//fields[i+1] = new JTextField();
					String array[] = values[i + 1].split(",");

					lengthMaqValues += array.length;

//					if (i < tips.length)
//						fields[i].setToolTipText(tips[i]);
//					if (i < widths.length)
//						fields[i].setColumns(widths[i]);
//
					//fields[i].setText(values[i + 1]);

					//JLabel lab = new JLabel(maquinariaLabels[i - 8],
						//	JLabel.LEFT);

					//lab = new JLabel("------------------", JLabel.LEFT);

					JPanel listLabelPanel = new JPanel(new GridLayout(
							array.length, 1));
					JPanel listPanel = new JPanel(new GridLayout(array.length,
							1));

					ArrayList<JTextField> secfields = new ArrayList<JTextField>();
					ArrayList<JCheckBox> secboxes = new ArrayList<JCheckBox>();

					for (int j = 0; j < array.length; j++) {

						// if (!(i == 7))
						secfields.add(new JTextField());
						secboxes.add(new JCheckBox());

						// if (!(i == 7))
						secfields.get(secfields.size() - 1).setColumns(6);
						secboxes.get(secboxes.size() - 1).setSelected(true);

						String arr[] = db.getMaquinariaValuesForProducto(id,
								i - 7, j).split(":");

					

						// if (!(i == 7))
						secfields.get(secfields.size() - 1).setText(arr[2]);

						maquinariaValues.add(arr[1]);

						fases.add(arr[0]);

						JLabel lab = new JLabel(array[j], JLabel.RIGHT);
						// if (!(i == 7))
						lab.setLabelFor(secfields.get(secfields.size() - 1));
						listLabelPanel.add(lab);
						JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
						if (!(i == 7))
							p.add(secfields.get(secfields.size() - 1));
						p.add(secboxes.get(secboxes.size() - 1));
						listPanel.add(p, BorderLayout.CENTER);
						//listform[i - 7].add(listLabelPanel);
						//listform[i - 7].add(listPanel);
						
						JPanel maquinaspanel = new JPanel();
						maquinaspanel.setLayout(new BoxLayout(maquinaspanel,
						BoxLayout.X_AXIS));
						maquinaspanel.add(listLabelPanel);
						maquinaspanel.add(listPanel);
						
						scrollpane[i - 7] = new JScrollPane(maquinaspanel);
						listform[i-7].add(scrollpane[i - 7],BorderLayout.CENTER);

						// secondaryfields.add(e)

					}

					secondaryfields[i - 7] = secfields;
					secondarycheckboxes[i - 7] = secboxes;

					// System.out.println("size checkbox=" + (i - 6) + ":"
					// + secondarycheckboxes[i - 6].size());

				} else {
					fields[i] = new JTextField();
					if (i < tips.length)
						fields[i].setToolTipText(tips[i]);
					if (i < widths.length)
						fields[i].setColumns(widths[i]);
					fields[i].setText(values[i + 1]);

					JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
					lab.setLabelFor(fields[i]);
					labelPanel.add(lab);
					JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
					p.add(fields[i]);
					if(i==4 || i==5) 
						p.add(boxes[i-3]);
					fieldPanel.add(p);
					
					if(i==6) {
						i++;
						fields[i] = new JTextField();
						if (i < tips.length)
							fields[i].setToolTipText(tips[i]);
						if (i < widths.length)
							fields[i].setColumns(widths[i]);
						fields[i].setText(values[i + 1]);

						lab = new JLabel(labels[i], JLabel.RIGHT);
						lab.setLabelFor(fields[i]);
						labelPanel.add(lab);
						p = new JPanel(new FlowLayout(FlowLayout.LEFT));
						p.add(boxes[0]);
						fieldPanel.add(p);
						i--;
					}
				}
			}
			System.out.println("values=" + Arrays.toString(values));
			if(values[values.length-3].equals("0")) {
				boxes[0].setSelected(false);
				for(int i =0; i<secondaryfields[2].size(); i++) {
				secondaryfields[2].get(i).setEnabled(false);
				secondarycheckboxes[2].get(i).setEnabled(false);
				}
			}
			else {
				boxes[0].setSelected(true);
			}
			if(values[values.length-2].equals("0")) {
				boxes[1].setSelected(false);
			}
			else {
				boxes[1].setSelected(true);
			}
			if(values[values.length-1].equals("0")) {
				boxes[2].setSelected(false);
			}
			else {
				boxes[2].setSelected(true);
			}


			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.PRODUCTO_MODIFICAR_CANCELAR);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.PRODUCTO_MODIFICAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);

			contentPane.add(form, BorderLayout.NORTH);
			contentPane.add(alllistforms, BorderLayout.CENTER);

			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);
			pack();

			setVisible(true);

		}

		public void actionPerformed(ActionEvent e) {

			ArrayList<String> fasesData;
			fasesData = new ArrayList<String>();
			
			String command = e.getActionCommand();

			values = new String[8];
			maqValues = new String[secondaryfields[0].size()
					+ secondaryfields[1].size() + secondaryfields[2].size()];
			maqModifications = new boolean[secondarycheckboxes[0].size()
					+ secondarycheckboxes[1].size()
					+ secondarycheckboxes[2].size()];
			values[0] = hiddenfield;

			if (command == Constants.PRODUCTO_MODIFICAR_CONFIRMACION) {

				boolean validunidad = true;
				boolean validtiempodispensacion = true;
				boolean validtiempoproduccion = true;
				boolean validetiquetadas = true;
				boolean validbandas = true;
				boolean validempacadas = true;

				boolean indicescheck[] = new boolean[] { true, true, true };
				boolean fieldscheck[] = new boolean[] { true, true };


				for (int i = 0; i < 3; i++) {
					fasesData.add(String.valueOf(boxes[i].isSelected()));
				}
				
				try {
					Integer.parseInt(fields[1].getText());

				} catch (Exception exp) {
					validunidad = false;
				}

				try {
					Float.parseFloat(fields[2].getText());

				} catch (Exception exp) {
					validtiempodispensacion = false;
				}

				try {
					Float.parseFloat(fields[3].getText());

				} catch (Exception exp) {
					validtiempoproduccion = false;
				}

				try {
					Integer.parseInt(fields[4].getText());

				} catch (Exception exp) {
					validetiquetadas = false;
				}

				try {
					Integer.parseInt(fields[5].getText());

				} catch (Exception exp) {
					validbandas = false;
				}

				try {
					Integer.parseInt(fields[6].getText());

				} catch (Exception exp) {
					validempacadas = false;
				}

				int selected[] = new int[] { 0, 0, 0 };

				for (int i = 0; i < 3; i++) {
					// System.out.println("size=" +
					// secondarycheckboxes[i].size());
					for (int j = 0; j < secondarycheckboxes[i].size(); j++) {
						if (((JCheckBox) (secondarycheckboxes[i].get(j)))
								.isSelected()) {
							selected[i]++;
						}
					}
				}

				for (int i = 0; i < 3; i++) {
					if (selected[i] == 0) {
						indicescheck[i] = false;
					}
				}

				for (int i = 1; i < 3; i++) {
					for (int j = 0; j < secondaryfields[i].size(); j++) {
						/*
						 * if (i == 0) { try { Float .parseFloat(((JTextField)
						 * (secondaryfields[i] .get(j))).getText());
						 * 
						 * } catch (Exception exp) { fieldscheck[i] = false; } }
						 * else {
						 */
						try {
							Integer.parseInt(((JTextField) (secondaryfields[i]
									.get(j))).getText());

						} catch (Exception exp) {
							fieldscheck[i] = false;
						}
						// }
					}
				}

				if (validtiempodispensacion && validtiempoproduccion
						&& validetiquetadas && validbandas && validempacadas
						&& indicescheck[0] && indicescheck[1]
						&& indicescheck[2] && fieldscheck[0] && fieldscheck[1]
						&& validunidad) {

					for (int i = 0; i < 7; i++) {
						values[i + 1] = fields[i].getText();
					}

					int count = 0;

					for (int i = 0; i < 3; i++) {
						for (int j = 0; j < secondaryfields[i].size(); j++) {
							maqValues[count] = ((JTextField) (secondaryfields[i]
									.get(j))).getText();
							count++;
						}
					}

					count = 0;

					for (int i = 0; i < 3; i++) {
						for (int j = 0; j < secondaryfields[i].size(); j++) {
							maqModifications[count] = ((JCheckBox) (secondarycheckboxes[i]
									.get(j))).isSelected();
							count++;
						}
					}

					System.out.println("values=" + Arrays.toString(values));

					db.modifyProducto(values, fasesData, Constants
							.singleArrayListToString(fases), Constants
							.singleArrayListToString(maquinariaValues),
							maqValues, maqModifications);
					listOfProductos = db.retrieveProductos();
					ptm.updateTable();
					setColumnWidth();
					modificarFrame.dispose();
				} else {
					JOptionPane
							.showMessageDialog(
									this,
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validunidad ? ""
													: "- Ingrese un numero valido para unidades en cc\n")
											+ (validtiempodispensacion ? ""
													: "- Ingrese un numero valido para tiempo de dispensacion\n")
											+ (validetiquetadas ? ""
													: "- Ingrese un numero valido para unidades etiquetadas por hora\n")
											+ (validbandas ? ""
													: "- Ingrese un numero valido para unidades bandas por hora\n")
											+ (validempacadas ? ""
													: "- Ingrese un numero valido para unidades empacadas por hora\n")
											+ (indicescheck[0] ? ""
													: "- Seleccione al menos una maquina para produccion\n")
											+ (indicescheck[1] ? ""
													: "- Seleccione al menos una maquina para llenado\n")
											+ (indicescheck[2] ? ""
													: "- Seleccione al menos una maquina para loteado\n")
											/*
											 * + (fieldscheck[0] ? "" :
											 * "- Ingrese un numero valido para tiempo de produccion lote por maquina \n"
											 * )
											 */
											+ (fieldscheck[0] ? ""
													: "- Ingrese un numero valido para unidades llenadas hora por maquina\n")
											+ (fieldscheck[1] ? ""
													: "- Ingrese un numero valido para unidades loteadas hora por maquina\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}

			} else if(command.equals(Constants.PRODUCTO_MODIFICAR_CANCELAR)) { 
				modificarFrame.dispose();
			}
		}
	}
}
